import { AxiosError } from "axios";
import router from "@/router";
import { useTitle } from "@vueuse/core";
import { useUserStore } from "@/store/user.ts";
import { RouteLocationNormalizedLoaded, RouteRecordRaw } from "vue-router";
import { NETWORK_ERROR_401 } from "@/utils/const.ts";

const allowList = ["/login", "/error", "/401", "/404", "/403"];
const loginPath = "/login";

router.beforeEach(async (to, _, next) => {
  // 获取
  const userStore = useUserStore();
  const token = localStorage.getItem("token");
  if (!token) {
    //  如果token不存在就跳转到登录页面
    if (!allowList.includes(to.path)) {
      next({
        path: loginPath,
      });
      return;
    }
  } else {
    if (!userStore.userInfo && !allowList.includes(to.path)) {
      try {
        // 获取用户信息
        await userStore.getUserInfo();
        // 获取路由菜单的信息
        const currentRoutes = await userStore.generateDynamicRoutes();
        currentRoutes.forEach((route: RouteRecordRaw) => {
          router.addRoute("rootPath", route);
        });
        next({
          path: to.path,
          replace: true,
        });
        return;
      } catch (e) {
        if (
          e instanceof AxiosError &&
          e?.response?.status === NETWORK_ERROR_401
        ) {
          // 跳转到error页面
          next({
            path: "/401",
          });
        }
      }
    } else {
      // 如果当前是登录页面就跳转到首页
      if (to.path === loginPath) {
        next({
          path: "/",
        });
        return;
      }
    }
  }
  next();
});

router.afterEach((to: RouteRecordRaw | RouteLocationNormalizedLoaded) => {
  const { title } = to.meta ?? {};
  // @ts-ignore
  useTitle(title);
});
